<?php

namespace app\modules\product\controllers;

use app\controllers\BaseController;
use app\services\DemandRecord;
use app\services\File;
use Yii;
use yii\helpers\Url;


class DemandRecordController extends BaseController
{
    /**
     * 新增需求备注
     * @method actionRecordCreate
     * @author ZhangYuan 574368565@qq.com
     * @time 2021/1/28 8:55
     */
    public function actionCreate()
    {
        $request = Yii::$app->request;
        $post = $request->post();

        if ($request->isPost) {
            $model = new DemandRecord();
            $model->load($post, '');
            if ($model->save()) {
                if (isset($post['attachment'])) File::batchSave($post['attachment'], 'demand-record', $model->id);
                $model->operation_log->create($this, "添加了需求 {$model->demand->title} 备注", Url::to(['/product/demand/view', 'id' => $model->demand_id]), true);
                return $this->success([], '保存成功');
            }
            return $this->error($model->errors);
        }

        return $this->render('create');
    }

    public function actionUpdate($id)
    {
        $request = Yii::$app->request;
        $post = $request->post();

        if ($request->isPost) {
            $model = DemandRecord::findOne(['id' => $post['id'], 'status' => 10]);
            $model->load($post, '');
            if ($model->save()) {
                if (isset($post['attachment'])) File::batchSave($post['attachment'], 'demand-record', $model->id);
                if (isset($post['attachment_remove'])) File::batchRemove($post['attachment_remove']);
                $model->operation_log->create($this, "编辑了需求 {$model->demand->title} 备注", Url::to(['/product/demand/view', 'id' => $model->demand_id]), true);
                return $this->success([], '编辑成功');
            }
            return $this->error($model->errors);
        }

        if (!$model = DemandRecord::findOne(['id' => $id, 'status' => 10])) {
            return $this->alert('未找到该备注');
        }

        return $this->render('update', ['model' => $model]);
    }

    public function actionDelete($id)
    {
        if (!$model = DemandRecord::findOne(['id' => $id, 'status' => 10])) {
            return $this->error('未找到该备注');
        }
        $model->status = 0;
        $model->save();
        $model->operation_log->create($this, "删除了需求 {$model->demand->title} 备注", Url::to(['/product/demand/view', 'id' => $model->demand_id]), true);
        return $this->success([], '删除成功');
    }
}
